package com.ceilcell.wx.atservice;

import com.ceilcell.wx.atservice.model.AccessToken;
import com.ceilcell.wx.atservice.model.WeiXinServerIP;
import com.ceilcell.wx.atservice.service.AccessTokenService;
import com.ceilcell.wx.atservice.service.WeiXinServerIPService;
import javafx.util.Builder;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

public class ScheduledGetAccessToken implements Runnable {

    private AccessTokenService accessTokenService;
    private WeiXinServerIPService weiXinServerIPService;

    public static class ScheduledPositionSenderBuilder implements Builder<ScheduledGetAccessToken> {

        private AccessTokenService accessTokenService;
        private WeiXinServerIPService weiXinServerIPService;

        public ScheduledPositionSenderBuilder accessTokenService(AccessTokenService accessTokenService){
            this.accessTokenService = accessTokenService;
            return this;
        }

        public ScheduledPositionSenderBuilder weixinServerIPService(WeiXinServerIPService weiXinServerIPService){
            this.weiXinServerIPService = weiXinServerIPService;
            return this;
        }

        public ScheduledGetAccessToken build(){
            return new ScheduledGetAccessToken(this);
        }
    }


    private ScheduledGetAccessToken(ScheduledPositionSenderBuilder builder){
        this.accessTokenService = builder.accessTokenService;
        this.weiXinServerIPService = builder.weiXinServerIPService;
    }

    private JSONObject HttpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new serviceX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            //log.error("Weixin server connection timed out.");
        } catch (Exception e) {
            //log.error("https request error:{}", e);
        }
        return jsonObject;
    }

    @Override
    public void run() {
        JSONObject accessTokenObject = HttpsRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9d3f77c38b0e3843&secret=384746be78dd74407b6f97fe663aa8ee","POST","");

        AccessToken accessToken = accessTokenService.findAccessTokenById(1);
        if(accessToken == null){
            accessToken = new AccessToken();
            accessToken.setTokenId(1);
            accessToken.setAccessToken(accessTokenObject.getString("access_token"));
            accessToken.setExpiresIn(accessTokenObject.getInt("expires_in"));
            accessTokenService.saveAccessToken(accessToken);
        }else{
            accessToken.setAccessToken(accessTokenObject.getString("access_token"));
            accessToken.setExpiresIn(accessTokenObject.getInt("expires_in"));

            accessTokenService.updateAccessToken(accessToken);
        }


        JSONObject ipListObject = HttpsRequest("https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=" + accessTokenObject.getString("access_token"),"GET","");
        JSONArray iplist = ipListObject.getJSONArray("ip_list");
        for (int i = 1; i <= iplist.size(); i++){

            WeiXinServerIP weiXinServerIP = weiXinServerIPService.findWeiXinServerIPById(i);

            if(weiXinServerIP == null){
                weiXinServerIP = new WeiXinServerIP();
                weiXinServerIP.setIpId(i+1);
                weiXinServerIP.setIpAddress(iplist.getString(i));

                weiXinServerIPService.saveWeiXinServerIP(weiXinServerIP);
            }else{
                weiXinServerIP.setIpAddress(iplist.getString(i));

                weiXinServerIPService.updateWeiXinServerIP(weiXinServerIP);
            }

        }
    }
}
